package com.elock.config;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.elock.common.AccessFilter;
import com.elock.common.AccessInterceptor;

@Configuration
public class WebAppConfigurer extends WebMvcConfigurerAdapter {

	/** 拦截器 */
	@Override
	public void addInterceptors(InterceptorRegistry registry) {

		registry.addInterceptor(new AccessInterceptor()).addPathPatterns("/**");
		super.addInterceptors(registry);
	}

	/** 过滤器 */
	@Bean
	public FilterRegistrationBean filterRegist() {

		FilterRegistrationBean frBean = new FilterRegistrationBean();
		frBean.setFilter(new AccessFilter());
		frBean.addUrlPatterns("*.html", "*.jsp", "*.jhtml");
		return frBean;
	}

	/** Servlet */
	@Bean
	public ServletRegistrationBean dispatcherServlet() {

		// 注解扫描上下文
		AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
		// base package
		// applicationContext.scan("com.elock");
		DispatcherServlet rest_dispatcherServlet = new DispatcherServlet(applicationContext);// 通过构造函数指定dispatcherServlet的上下文
		ServletRegistrationBean registrationBean = new ServletRegistrationBean(rest_dispatcherServlet);// 用ServletRegistrationBean包装servlet
		registrationBean.setLoadOnStartup(1);
		registrationBean.addUrlMappings("*.jhtml");// 指定urlmapping
		// registrationBean.setName("");//指定name，如果不指定默认为dispatcherServlet
		return registrationBean;
	}

	// 显示声明CommonsMultipartResolver为mutipartResolver
	@Bean(name = "multipartResolver")
	public MultipartResolver multipartResolver() {
		CommonsMultipartResolver resolver = new CommonsMultipartResolver();
		resolver.setDefaultEncoding("UTF-8");
		resolver.setResolveLazily(true);// resolveLazily属性启用是为了推迟文件解析，以在在UploadAction中捕获文件大小异常
		resolver.setMaxInMemorySize(40960);
		resolver.setMaxUploadSize(5 * 1024 * 1024);// 上传文件大小 5M 5*1024*1024
		return resolver;
	}
}
